package com.ease.framework.gef4p.model {
   import com.ease.util.collections.HashMap;
   import com.ease.util.collections.Map;
   import com.ease.framework.gef.events.ModelEvent;

   import mx.collections.ArrayCollection;

   public class ModelInstanceCache {

      private static var uidModelMap:Map = new HashMap();
      private static var idModelMap:Map = new HashMap();

      public function ModelInstanceCache() {
      }

      public static function addModel(model:PModel):void {
         uidModelMap.put(model.uuid, model);
         if (model.id == "") {
            model.addEventListener(ModelEvent.ModelEvent_CHANGED, modelChangeHandle);
         }
         else {
            idModelMap.put(model.id, model);
         }

         function modelChangeHandle(evt:ModelEvent):void {

            var pmodel:PModel = evt.model as PModel;

            if (pmodel) {

               if (evt.oldValue.containsKey("id")) {

                  var oldID:String = evt.oldValue.getObject("id") + "";

                  if (oldID != "") {
                     idModelMap.remove(oldID);
                  }
                  addModel(pmodel);

               }

            }

         }
      }

      public static function removeModel(model:PModel):void {
         uidModelMap.remove(model.uuid);
      }

      public static function getModelByUid(key:String):PModel {
         return uidModelMap.getObject(key) as PModel;
      }

      public static function getModelById(key:String):PModel {
         return idModelMap.getObject(key) as PModel;
      }

      public static function get models():ArrayCollection {
         return new ArrayCollection(uidModelMap.values());
      }

   }
}